package cn.tiger.exception;

import cn.tiger.common.Result;
import cn.tiger.common.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class CommonControllerAdvice {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result<?> handleBusinessException(BusinessException ex) {
        log.warn("[业务异常] 出现业务异常：", ex);
        return Result.error(ex.getCodeMsg());
    }
    
    @ExceptionHandler(ConversationException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleConversationException(ConversationException ex) {
        log.warn("[对话异常] 出现对话异常：{}", ex.getCodeMsg().getMsg());
        log.info("返回CodeMsg: code={}, msg={}", ex.getCodeMsg().getCode(), ex.getCodeMsg().getMsg());
        
        Result<?> result = Result.error(ex.getCodeMsg());
        log.info("返回结果: {}", result);
        
        // 返回HTTP状态码和响应体
        return ResponseEntity.status(ex.getCodeMsg().getCode()).body(result);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<?> handleDefaultException(Exception ex) {
        //在控制台打印错误消息.
        log.error("[通用异常处理] 出现系统异常", ex);
        return Result.defaultError();
    }
}
